import httpProxy from 'http-proxy';
import Chalk from 'chalk';
import Config from '../config';

let Proxy = httpProxy.createProxyServer({
// ssl: {
//   key: fs.readFileSync('../lets/famanoder.com-key.pem', 'utf8'),
//   cert: fs.readFileSync('../lets/famanoder.com-crt.pem', 'utf8')
// },
// secure: false
});

Proxy.on('proxyReq',(proxyReq,req,res,opts)=>{
	
	if (Config.showRequestLogs) req.__time=Date.now();
	/* 
	* set origin remote ip on headers
	*/
	if (Config.xForwardIP) {
	  let matchIP=req.connection.remoteAddress.match(/:([\d\.]+)$/);
	  matchIP&&proxyReq.setHeader('x-forward-ip',matchIP[1]);
	};

});

Proxy.on('proxyRes', function (proxyRes, req, res) {
	/*
	* show request logs [method statusCode url time]
	*/
	if (Config.showRequestLogs) {
        let resCode=proxyRes.statusCode;
        console.log(`${Chalk.blue(req.method)} ${resCode==200?Chalk.green(resCode):
                                                resCode==304||resCode==302?Chalk.yellow(resCode):
                                                resCode==404||resCode==500||resCode==400?Chalk.red(resCode):
                                                resCode} ${req.url} ${Date.now()-req.__time}ms`);
    	req.__time=null;
    };
  // console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2));
});
  
Proxy.on('error', (err,req,res)=> {
	/*
    * catch proxy error
    */
    res.writeHead(500,{
        'Content-Type':'text/html'
    });
    console.log(Chalk.red(500+' proxy error occured ... ')+'\n');
    console.log(err);
    res.write('<b>500</b> Internal Server Error:</br>');
    res.end(err.message);
});

export default Proxy;